#!/usr/bin/env python3
"""
Python 3.8 兼容性检查和安装脚本
"""

import sys
import subprocess
import os

def check_python_version():
    """检查Python版本"""
    version = sys.version_info
    print(f"当前Python版本: {version.major}.{version.minor}.{version.micro}")
    
    if version.major != 3:
        print("❌ 错误: 需要Python 3.x版本")
        return False
    
    if version.minor < 8:
        print("❌ 错误: 需要Python 3.8或更高版本")
        return False
    
    if version.minor == 8:
        print("✅ Python 3.8 检测到，将使用兼容版本的依赖包")
        return "py38"
    else:
        print("✅ Python 3.9+ 检测到，可以使用标准版本的依赖包")
        return "standard"

def install_dependencies(version_type):
    """安装依赖包"""
    if version_type == "py38":
        requirements_file = "requirements_py38.txt"
        print("正在安装Python 3.8兼容版本的依赖包...")
    else:
        requirements_file = "requirements.txt"
        print("正在安装标准版本的依赖包...")
    
    if not os.path.exists(requirements_file):
        print(f"❌ 错误: {requirements_file} 文件不存在")
        return False
    
    try:
        # 升级pip
        print("升级pip...")
        subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade", "pip"])
        
        # 安装依赖
        print(f"从 {requirements_file} 安装依赖...")
        subprocess.check_call([
            sys.executable, "-m", "pip", "install", 
            "-r", requirements_file,
            "-i", "https://pypi.tuna.tsinghua.edu.cn/simple"  # 使用清华镜像加速
        ])
        
        print("✅ 依赖安装完成")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ 依赖安装失败: {e}")
        print("\n尝试解决方案:")
        print("1. 检查网络连接")
        print("2. 尝试手动安装: pip install -r requirements_py38.txt")
        print("3. 使用虚拟环境: python -m venv venv && venv\\Scripts\\activate")
        return False

def test_imports():
    """测试导入关键模块"""
    print("测试模块导入...")
    
    modules = ['flask', 'flask_cors', 'redis', 'dotenv']
    failed_modules = []
    
    for module in modules:
        try:
            __import__(module)
            print(f"✅ {module} 导入成功")
        except ImportError as e:
            print(f"❌ {module} 导入失败: {e}")
            failed_modules.append(module)
    
    if failed_modules:
        print(f"\n❌ 以下模块导入失败: {', '.join(failed_modules)}")
        return False
    else:
        print("✅ 所有模块导入成功")
        return True

def main():
    print("=" * 60)
    print("Python 3.8 兼容性检查和安装脚本")
    print("=" * 60)
    
    # 检查Python版本
    version_type = check_python_version()
    if not version_type:
        return
    
    # 安装依赖
    if not install_dependencies(version_type):
        return
    
    # 测试导入
    if not test_imports():
        return
    
    print("\n" + "=" * 60)
    print("✅ 环境设置完成！")
    print("现在可以运行: python app.py")
    print("=" * 60)

if __name__ == "__main__":
    main()
